import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
import createPersistedState from 'vuex-persistedstate'
import {capexProcessSchedule} from "@/store/types";
Vue.use(Vuex)
const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
    const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
    const value = modulesFiles(modulePath)
    modules[moduleName] = value.default
    return modules
}, {})

let state = {
    token: '',
    loadingPage: 0,
    oneClickImportSelectedDevices:[],
    dncTreeSelectedItem: {},
    title:'',
    userInfo: '',
    menuScale:false,
    capexProcessSchedule:{}
};

state.token = localStorage.getItem("ziyunFactoryPortalToken");
//在页面加载时读取localStorage里的状态信息
let equipmentMsg = localStorage.getItem("equipmentMsg");
if(equipmentMsg){
    let data = JSON.parse(equipmentMsg);
    data.token = localStorage.getItem("ziyunFactoryPortalToken");
    state = Object.assign(state,data)
   
}


//在页面刷新时将vuex里的信息保存到localStorage里
window.addEventListener("beforeunload",()=>{
    state.loadingPage = 0;  // 保持默认值
    state.token = localStorage.getItem("ziyunFactoryPortalToken");
    localStorage.setItem("equipmentMsg",JSON.stringify(state))
});

export const $store =  new Vuex.Store({
    state,
    mutations,
    actions,
    modules,
    getters,
    plugins: [createPersistedState({
        storage:window.sessionStorage,
        reducer(state) {
            return {
                detail: state.detail,
                capex: state.capex,
                capexProcessSchedule:state.capexProcessSchedule
            }
        }
    })]
})


export  default $store
